package com.senlingspace.quartz.task;

import com.senlingspace.common.core.dingtalk.DingTalkService;
import com.senlingspace.system.domain.DomainSSLCertificate;
import com.senlingspace.system.mapper.DomainSSLCertificateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * SSL 证书过期检查任务
 *
 * @author lebronjames
 * @date 2024/09/10
 */
@Slf4j
@Component
public class SSLExpiryCheckTask {

    @Autowired
    private DomainSSLCertificateMapper domainSSLMapper;
    @Autowired
    private DingTalkService dingTalkService;


    @Scheduled(cron = "0 0 9 * * ?")  // 每天9点运行
    public void checkSSLExpiry() {
        log.info("开始检查 SSL 证书过期状态...");
        // 查询即将在15天内过期的 SSL 证书
        List<DomainSSLCertificate> expiringSSLs = domainSSLMapper.selectExpiringSSL(15);

        for (DomainSSLCertificate domainSSL : expiringSSLs) {
            long daysUntilExpiry = LocalDate.now().until(domainSSL.getSslExpiryDate()).getDays();

            // 发送钉钉通知，每个域名只会通知一次
            String message = String.format(
                    "⚠️警告：域名 %s 的 SSL 证书将在 %d 天后过期（到期日期：%s），请尽快更新。",
                    domainSSL.getDomainName(),
                    daysUntilExpiry,
                    domainSSL.getSslExpiryDate()
            );
            dingTalkService.sendTextMessage(message, true);

            // 更新通知状态
            domainSSL.setNotificationStatus(1);
            domainSSL.setLastNotifiedDate(LocalDate.now());
            domainSSLMapper.updateNotificationStatus(domainSSL.getId(), 1, LocalDate.now());
        }
        log.info("SSL 证书过期检查任务结束。");
    }

}
